import { defineStore } from "pinia";
import { fieldFactory } from "@/views/FormGenerator/util";
import { isTableHelperColumn } from "@/utils";

export const useFormStore = defineStore("form", {
  state: () => {
    return {
      templateFile:
        localStorage.getItem("form-templateFile") || "Antd-FormModal",
      wrapFormFieldToken: true,
      wrapReadonlyToken: false,
      globalConfig: {
        layoutConfig: {
          formLayout: {
            // horizontal | vertical | inline
            layout: "horizontal",
            labelCol: {
              span: 5,
            },
            wrapperCol: {
              span: 19,
            },
            labelWidth: 100,
          },
          row: { gutter: 20 },
          col: { span: 8 },
        },
        tablePage: false,
      },
      fieldList: [
        fieldFactory("groupForm", "", "default", [
          fieldFactory("input"),
          fieldFactory("select"),
          fieldFactory("date-picker"),
          fieldFactory("range-picker"),
          fieldFactory("textarea"),
        ]),
      ],
      set columnNum(num) {
        this.globalConfig.layoutConfig.col.span = 24 / num;
      },
      get columnNum() {
        return 24 / this.globalConfig.layoutConfig.col.span;
      },
    };
  },
  getters: {
    isElement: (state) => state.templateFile.startsWith("Element"),
    uiType: (state) => {
      const templateStr = state.templateFile;
      return templateStr.slice(0, templateStr.lastIndexOf("-"));
    },
  },
  actions: {
    setTemplateFile(templateFile) {
      localStorage.setItem("form-templateFile", templateFile);
      this.templateFile = templateFile;
    },
    handleAxureData(data) {
      const { type, config, formObj } = data;
      console.log(
        "🚀 ~ handleAxureData ~ type, config, formObj:",
        type,
        config,
        formObj
      );
      if (type === "form") {
        this.fieldList = [];
        if (config) {
          this.columnNum = config.colNum;
        }
        const { default: defaultKey, ...subForms } = formObj;
        this.fieldList.push(
          fieldFactory(
            "groupForm",
            defaultKey.label,
            "default",
            defaultKey.fieldList
          )
        );
        for (const subFormKey of Object.keys(subForms)) {
          const fieldLabel = subForms[subFormKey].fieldList
            .map((field) => field.label)
            .some((label) => isTableHelperColumn(label));
          console.log("🚀 ~ handleAxureData ~ fieldLabel:", fieldLabel);

          const tableType = fieldLabel ? "subForm" : "groupForm";
          const subFormField = fieldFactory(
            tableType,
            subForms[subFormKey].label,
            subForms[subFormKey].formKey,
            subForms[subFormKey].fieldList
          );
          this.fieldList.push(subFormField);
        }
        console.log("🚀 ~ handleAxureData ~ this.fieldList:", this.fieldList);
      }
    },
  },
});
